// 校验传入的数据是否合法
const errorType  = require('../constant/errTypes');
const connections = require('../app/database')
const service= require('../services/users.service')
const passwordHandler = require('../utils/passwordHandler')
const verifyUser =async function (ctx,next){
    const {name,password} = ctx.request.body;
    if(!name || !password){
        const error = new Error(errorType.NAME_OR_PASSWORD_IS_INVALID);
        return ctx.app.emit('error', error,ctx);
    }
    // 查询数据库中是否存在该用户
    const result = await service.getUserByName(name);
    if(result[0] !== undefined){
        const error = new Error(errorType.NAME_OR_PASSWORD_IS_EXIST);
        return ctx.app.emit('error', error, ctx);
    }
       await next();
}
// 注册用户
const handlePassword =async function(ctx, next) {
    let {name,password} = ctx.request.body;
    // 对密码进行加密
    ctx.request.body.password = passwordHandler(password);  // 对密码进行加密
    await next();
}
// 注册用户
module.exports={
    verifyUser,
    handlePassword
}